package com.example.neutonote2.ui.tags;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.neutonote2.R;
import com.example.neutonote2.data.model.Tag;
import com.example.neutonote2.viewmodel.TagViewModel;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.List;

public class TagListFragment extends Fragment {

    private TagViewModel tagViewModel;
    private RecyclerView recyclerView;
    private TextView textNoTags;
    private FloatingActionButton fabAddTag;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_tag_list, container, false);

        // 初始化视图
        recyclerView = root.findViewById(R.id.recycler_view_tags);
        textNoTags = root.findViewById(R.id.text_no_tags);
        fabAddTag = root.findViewById(R.id.fab_add_tag);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 暂时使用空的适配器，后续补充实现
        recyclerView.setAdapter(new TagAdapter(new ArrayList<>(), tag -> {
            // 编辑标签的功能，后续实现
        }));

        // 设置FAB点击事件
        fabAddTag.setOnClickListener(v -> showAddTagDialog());

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化ViewModel
        tagViewModel = new ViewModelProvider(requireActivity()).get(TagViewModel.class);
        
        // 清理无效标签（网络错误信息等）
        tagViewModel.cleanInvalidTags();

        // 加载标签
        tagViewModel.getAllTags().observe(getViewLifecycleOwner(), tags -> {
            if (tags != null && !tags.isEmpty()) {
                // 过滤掉错误消息
                List<Tag> validTags = filterValidTags(tags);
                
                if (!validTags.isEmpty()) {
                    textNoTags.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    ((TagAdapter) recyclerView.getAdapter()).updateTags(validTags);
                } else {
                    textNoTags.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                }
            } else {
                textNoTags.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        });
    }

    private void showAddTagDialog() {
        // 创建对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_tag, null);
        TextInputEditText editTagName = dialogView.findViewById(R.id.edit_tag_name);
        TextInputEditText editTagColor = dialogView.findViewById(R.id.edit_tag_color);
        TextInputLayout layoutTagName = dialogView.findViewById(R.id.layout_tag_name);
        TextInputLayout layoutTagColor = dialogView.findViewById(R.id.layout_tag_color);

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("新建标签")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = editTagName.getText().toString().trim();
                    String color = editTagColor.getText().toString().trim();

                    if (name.isEmpty()) {
                        layoutTagName.setError("请输入标签名称");
                        return;
                    }

                    if (color.isEmpty()) {
                        color = "#3F51B5"; // 默认颜色
                    }

                    // 保存标签
                    Tag newTag = new Tag(name, color);
                    tagViewModel.insert(newTag);
                    Toast.makeText(requireContext(), "标签已创建", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 过滤有效的标签，去除错误消息
     */
    private List<Tag> filterValidTags(List<Tag> tags) {
        List<Tag> validTags = new ArrayList<>();
        for (Tag tag : tags) {
            if (tag != null && tag.getName() != null && 
                !isErrorMessage(tag.getName()) && 
                tag.getName().length() < 20) {
                validTags.add(tag);
            }
        }
        return validTags;
    }
    
    /**
     * 检查标签名称是否为错误消息
     */
    private boolean isErrorMessage(String tagName) {
        String lowerCase = tagName.toLowerCase();
        return lowerCase.contains("unable to resolve host") || 
               lowerCase.contains("no address associated") ||
               lowerCase.contains("failed to connect") ||
               lowerCase.contains("exception") ||
               lowerCase.contains("error") ||
               lowerCase.contains("故障") ||
               lowerCase.contains("失败") ||
               lowerCase.contains("错误") ||
               lowerCase.contains("异常") ||
               lowerCase.contains("://");
    }

    // 定义标签点击监听器接口
    interface OnTagClickListener {
        void onTagClick(Tag tag);
    }

    // 内部适配器类
    private class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
        private List<Tag> tags;
        private final OnTagClickListener listener;

        public TagAdapter(List<Tag> tags, OnTagClickListener listener) {
            this.tags = tags;
            this.listener = listener;
        }
        
        public void updateTags(List<Tag> newTags) {
            this.tags = newTags;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public TagViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            // 使用自定义布局，而不是simple_list_item_1
            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_tag, parent, false);
            return new TagViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull TagViewHolder holder, int position) {
            Tag tag = tags.get(position);
            
            // 设置标签名称
            holder.tagName.setText(tag.getName());
            
            // 设置标签颜色
            try {
                int color = android.graphics.Color.parseColor(tag.getColor());
                holder.tagColor.setBackgroundColor(color);
                // 不管背景颜色深浅，所有文字都使用黑色
                holder.tagName.setTextColor(android.graphics.Color.BLACK);
            } catch (IllegalArgumentException e) {
                // 如果颜色格式无效，使用默认颜色
                holder.tagColor.setBackgroundColor(android.graphics.Color.DKGRAY);
                holder.tagName.setTextColor(android.graphics.Color.BLACK);
            }
            
            // 点击事件 - 编辑标签
            holder.itemView.setOnClickListener(v -> {
                showEditTagDialog(tag);
            });
            
            // 长按事件 - 删除标签
            holder.itemView.setOnLongClickListener(v -> {
                new MaterialAlertDialogBuilder(requireContext())
                    .setTitle("删除标签")
                    .setMessage("确定要删除标签 \"" + tag.getName() + "\" 吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        tagViewModel.delete(tag);
                        Toast.makeText(requireContext(), "标签已删除", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
                return true;
            });
        }

        @Override
        public int getItemCount() {
            return tags.size();
        }

        class TagViewHolder extends RecyclerView.ViewHolder {
            TextView tagName;
            View tagColor;
            
            public TagViewHolder(@NonNull View itemView) {
                super(itemView);
                tagName = itemView.findViewById(R.id.text_tag_name);
                tagColor = itemView.findViewById(R.id.view_tag_color);
            }
        }
    }
    
    /**
     * 显示编辑标签对话框
     */
    private void showEditTagDialog(Tag tag) {
        // 创建对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_tag, null);
        TextInputEditText editTagName = dialogView.findViewById(R.id.edit_tag_name);
        TextInputEditText editTagColor = dialogView.findViewById(R.id.edit_tag_color);
        TextInputLayout layoutTagName = dialogView.findViewById(R.id.layout_tag_name);
        TextInputLayout layoutTagColor = dialogView.findViewById(R.id.layout_tag_color);
        
        // 设置现有值
        editTagName.setText(tag.getName());
        editTagColor.setText(tag.getColor());

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("编辑标签")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String name = editTagName.getText().toString().trim();
                    String color = editTagColor.getText().toString().trim();

                    if (name.isEmpty()) {
                        layoutTagName.setError("请输入标签名称");
                        return;
                    }

                    if (color.isEmpty()) {
                        color = "#3F51B5"; // 默认颜色
                    }

                    // 更新标签
                    tag.setName(name);
                    tag.setColor(color);
                    tagViewModel.update(tag);
                    Toast.makeText(requireContext(), "标签已更新", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 